// pages/roomDetail/roomDetail.js
var common = require("../../utils/common.js");
//index.js
//获取应用实例
const app = getApp()
var circles = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIndex: 0,
    oldImage: '../../img/old.png',
    isActivePrice: true,
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    isInputShow: false,
    inputValue: '',
    city: '',
    latitude: '',
    longitude: '',
    allCondition: {
      "city": "",
      "cityName": ""
    },
    roomIndex: -1, //第几条
    length: 10,
    total: 0, //共多少条
    adviserList: [],
    orderBy: 'def',
    scrollClass: false,
    isOver: false,
    hasWaterLogo: false, //是否有水印
    islazy:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    _this.imageLoad();
    if (options.city && options.city != "") {
      var city = options.city;

      //获取从city传来的数据
      if (city.indexOf('市') > 0) {
        city = city.substring(0, city.indexOf('市'));
      }
      _this.setData({
        allCondition: {
          cityName: options.city
        },
        city: city
      })

      wx.request({
        url: encodeURI('https://apis.map.qq.com/ws/place/v1/suggestion/'),
        data: {
          region: encodeURIComponent(_this.data.city),
          keyword: _this.data.keyword,
          key: "EJMBZ-QPFRP-RUYDA-VPHF3-YXXKE-3ZFYQ"
        },
        header: {
          "Content-Type": "application/json"
        },
        success: function(res) {
          var data = res.data.data[0].location;
          _this.setData({
            latitude: data.lat,
            longitude: data.lng
          })
          _this.queryWlpXcxByParams();
        },
        fail: function() {
          wx.showToast({
            title: '您选择了取消1',
          })
        }
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this;
    if (_this.data.city && _this.data.city != '') {

    } else {
      wx.getLocation({
        type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
        success: function(res) {
          wx.request({
            url: 'https://apis.map.qq.com/ws/geocoder/v1/',
            data: {
              location: res.latitude + "," + res.longitude,
              key: "EJMBZ-QPFRP-RUYDA-VPHF3-YXXKE-3ZFYQ"
            },
            header: {
              "Content-Type": "application/json"
            },
            success: function(res) {
              //console.log(res);
              var city = res.data.result.address_component.city;
              app.globalData.nowCity = city;
              if (city.indexOf('市') > 0) {
                city = city.substring(0, city.indexOf('市'));
              }
              _this.setData({
                city: city,
                latitude: res.data.result.location.lat,
                longitude: res.data.result.location.lng
              })
              _this.queryWlpXcxByParams();
            }
          })
        },
        fail: function(res) {
          wx.showModal({
            title: '用户未授权',
            content: '如需正常使用小程序，请点击授权按钮，勾选用户信息并点击确定。',
            showCancel: false,
            success: function(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(res) {
                    console.log(res);
                    if (!res.authSetting['scope.userLocation']) {
                      _this.queryWlpXcxByParams();
                    }
                  }
                })
              }
            }
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    //console.log("到底了")
    var that = this;
    that.queryBuildingList();
  },

  scrollBottom: function() {
    // console.log("到底了")
    var that = this;
    that.queryBuildingList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var titleName = this.data.titleName;
    return {
      title: titleName,
      path: '/pages/roomDetail/roomDetail',
      success: function(res) {
        // 转发成功
        // console.log(2)
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  typeActive: function(e) {
    var that = this;
    var nowIndex = e.currentTarget.dataset.index;
    var orderBy = e.currentTarget.dataset.order;
    if (nowIndex == '1') {
      if (that.data.isActivePrice) {
        that.setData({
          activeIndex: nowIndex,
          oldImage: '../../img/top_price.png',
          isActivePrice: false,
          orderBy: "priceup"
        })
      } else {
        that.setData({
          activeIndex: nowIndex,
          oldImage: '../../img/lower_price.png',
          isActivePrice: true,
          orderBy: "pricedrop"
        })
      }
    } else {
      that.setData({
        activeIndex: nowIndex,
        oldImage: '../../img/old.png',
        isActivePrice: true,
        orderBy: orderBy
      })
    }

    that.setData({
      roomIndex: -1, //第几条
      length: 10,
      total: 0, //共多少条
      adviserList: [],
    })
    that.queryBuildingList();
  },

  inputContent: function(e) {
    //input输入内容，显示取消
    var that = this;
    var indexValue = e.detail.value;
    if (indexValue != "") {
      //input的值不等于空时
      that.setData({
        inputValue: e.detail.value,
        isInputShow: true
      })
    } else {
      that.setData({
        inputValue: e.detail.value,
        isInputShow: false,
        roomIndex: -1, //第几条
        length: 10,
        total: 0, //共多少条
        adviserList: [],
      })
      that.queryBuildingList();
    }
  },

  removeF: function() {
    //清空搜索框的数据
    var that = this;
    var inputValue = that.data.inputValue;
    that.setData({
      inputValue: '',
      isInputShow: false
    })
  },

  confirmF: function() {
    //点击搜索时触发
    var that = this;
    that.setData({
      roomIndex: -1, //第几条
      length: 10,
      total: 0, //共多少条
      adviserList: [],
    })
    that.queryBuildingList();
  },

  gotoCity: function() {
    //跳转到城市选择
    var that = this;
    var city = that.data.city;
    wx.navigateTo({
      url: '../city/city?city=' + city,
    })
  },


  queryWlpXcxByParams: function() {
    var _that = this;
    common.ajaxPost(
      'portal/wlpXcx/queryWlpXcxByParams.action', {
        appId: 'wx067ac066b8ee77fd'
      },
      function(res) {
        //console.log(res);
        if (res.data) {
          app.globalData.queryWlpXcxByParams = res.data;
          if (app.globalData.queryWlpXcxByParams) {
            wx.setNavigationBarTitle({
              title: "微楼盘"
            });
            _that.setData({
              titleName: res.data[0].name
            })
            //查詢banner
            _that.queryWlpBannerList();
            _that.queryBuildingList();
            console.log(app)
          }
        }
      })
  },

  queryWlpBannerList: function() {
    var _that = this;
    common.ajaxPost(
      'portal/wlpBanner/queryWlpBannerList.action', {
        xcxId: app.globalData.queryWlpXcxByParams[0].id
      },
      function(res) {
        if (res.list && res.list.length > 0) {
          //banner存在
          var list = res.list;
          var imgsList = [];
          for (var i = 0; i < list.length; i++) {
            imgsList.push(list[i].imgUrl);
          }
          _that.setData({
            imgUrls: imgsList,
            imgAllUrl: list,
          })
        }
      })
  },

  queryBuildingList: function() {
    //查詢列表
    // console.log(app);
    var that = this;
    var index = that.data.roomIndex;
    var length = that.data.length;
    var orderBy = that.data.orderBy;
    var name = that.data.inputValue;
    var city = that.data.city;
    if (index <= that.data.total) {
      index++;
      common.ajaxPost(
        'portal/wlpBuilding/queryBuildingList.action', {
          start: index,
          length: length,
          xcxId: app.globalData.queryWlpXcxByParams.id,
          addstr: city,
          name: name,
          orderBy: orderBy
        },
        function(res) {
          console.log(res);
          if (res && res.length > 0) {
            if (app.globalData.xcxtype.hasLogo == '1') {
              //显示水印
              that.setData({
                hasWaterLogo: true
              })
            } else {
              that.setData({
                hasWaterLogo: false
              })
            }
            var list = that.data.adviserList;
            list = list.concat(res.data);
            that.setData({
              adviserList: list,
              total: res.recordsTotal,
              roomIndex: that.data.roomIndex + res.length
            })
            // console.log(that.data.adviserList.length)
            that.list(that.data.adviserList);
            if (res.recordsTotal == 0) {
              wx.showToast({
                title: '暂无数据',
                icon: 'none'
              })
            }
          }
        }
      )
    } else {
      // wx.showToast({
      //   title: '没有更多了',
      //   icon: 'none'
      // })
      that.setData({
        isOver: true
      })
    }
  },

  list: function(list) {
    var that = this;
    for (var i = 0; i < list.length; i++) {
      var coverImg = "adviserList[" + i + "].coverPic";
      var coverNewImg = list[i].coverPic.split(";")[0];
      var tip;
      var up = "adviserList[" + i + "].houseType";
      if (list[i].houseType != 1 && list[i].houseType != 2 && list[i].houseType != 3 && list[i].houseType != 4 && list[i].houseType != 5 && list[i].houseType != 6 && list[i].houseType != 7) {
        tip = list[i].houseType
      } else {
        tip = that.houseType(list[i].houseType);
      }
      that.setData({
        [up]: tip,
        [coverImg]: coverNewImg
      })

      if (list[i].houseLable.indexOf("|") === -1) {
        if (typeof(list[i].houseLable) == "string") {
          var houseLable = list[i].houseLable;
          var house = [];
          house.push(houseLable)
          var houseLableUp = "adviserList[" + i + "].houseLable"
          that.setData({
            [houseLableUp]: house
          })
        }
      } else {
        var houseLable = list[i].houseLable.split("|");
        var houseLableUp = "adviserList[" + i + "].houseLable"
        that.setData({
          [houseLableUp]: houseLable
        })
      }
      //  console.log(typeof (list[i].houseLable))
    }
    that.setData({
      newList: list,
      islazy:false
    })
  },

  gotoDetail: function(e) {
    var id = e.currentTarget.dataset.id;
    app.globalData.lpid = id;
    common.addBuildingPV(id);

    if (app.globalData.bid != "") {
      if (id == app.globalData.bid) {
        app.globalData.bid = id;
        wx.navigateTo({
          url: '../index/index?isIndex=1',
        })
      } else {
        app.globalData.bid = id;
        wx.navigateTo({
          url: '../index/index',
        })
      }
    } else {
      app.globalData.bid = id;
      wx.navigateTo({
        url: '../index/index',
      })
    }

  },

  houseType: function(type) {
    switch (type) {
      case 1:
        return '住宅';
        break;
      case 2:
        return '公寓';
        break;
      case 3:
        return '别墅';
        break;
      case 4:
        return '商铺';
        break;
      case 5:
        return '经济适用房';
        break;
      case 6:
        return '两限房';
        break;
      case 7:
        return '综合体';
        break;
      default:
        break;
    }
  },


  gotoUrl: function(e) {
    var id = e.currentTarget.dataset.id;
    // app.globalData.lpid = id;
    // app.globalData.bid = id;
    // common.addBuildingPV(id); 
    //console.log(e.currentTarget.dataset.type + "---------" + e.currentTarget.dataset.typeinfo);
    if (e.currentTarget.dataset.type == "1") {
      return false;
    } else if (e.currentTarget.dataset.type == "2") {
      app.globalData.lpid = (e.currentTarget.dataset.typeinfo);
      app.globalData.bid = (e.currentTarget.dataset.typeinfo);
      common.addBuildingPV(e.currentTarget.dataset.typeinfo);
      wx.navigateTo({
        url: '../index/index',
      })
    } else if (e.currentTarget.dataset.type == "3") {
      wx.navigateTo({
        url: '/pages/webView2/webView2?vrurl1=https://xnzx.diandianja.com/Webim/urk.html' + '&vrurl=https://www.baidu.com',
      })
    }
  },

  scrolls: function(e) {
    // console.log(e);
    var that = this;
    var scrollTop = e.detail.scrollTop;
    if (scrollTop >= 80) {
      that.setData({
        scrollClass: true
      })
    } else {
      that.setData({
        scrollClass: false
      })
    }
  },


  imageLoad: function() {
    var that = this;
    that.setData({
      scrollHeight: wx.getSystemInfoSync().windowHeight
    })
  },
  drawImg: function() {
    const ctx = wx.createCanvasContext('firstCanvas')

    const pattern = ctx.createPattern('./../img/add.png', 'repeat-x')
    ctx.fillStyle = pattern
    ctx.fillRect(0, 0, 300, 150)

    // Draw coordinates
    ctx.arc(100, 75, 50, 0, 2 * Math.PI)
    ctx.setFillStyle('#EEEEEE')
    ctx.fill()

    ctx.beginPath()
    ctx.moveTo(40, 75)
    ctx.lineTo(160, 75)
    ctx.moveTo(100, 15)
    ctx.lineTo(100, 135)
    ctx.setStrokeStyle('#AAAAAA')
    ctx.stroke()

    ctx.setFontSize(12)
    ctx.setFillStyle('black')
    ctx.fillText('0', 165, 78)
    ctx.fillText('0.5*PI', 83, 145)
    ctx.fillText('1*PI', 15, 78)
    ctx.fillText('1.5*PI', 83, 10)

    // Draw points
    ctx.beginPath()
    ctx.arc(100, 75, 2, 0, 2 * Math.PI)
    ctx.setFillStyle('lightgreen')
    ctx.fill()

    ctx.beginPath()
    ctx.arc(100, 25, 2, 0, 2 * Math.PI)
    ctx.setFillStyle('blue')
    ctx.fill()

    ctx.beginPath()
    ctx.arc(150, 75, 2, 0, 2 * Math.PI)
    ctx.setFillStyle('red')
    ctx.fill()

    // Draw arc
    ctx.beginPath()
    ctx.arc(100, 75, 50, 0, 1.5 * Math.PI)
    ctx.setStrokeStyle('#333333')
    ctx.stroke()

    ctx.draw()
  }
})